package com.zywl.web.utils.tags;

import com.alibaba.fastjson.JSONObject;
import com.zywl.core.beans.Dictionary;
import com.zywl.utils.utils.Constants;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;

public class DictionaryTranslation extends SimpleTagSupport {
    private String type;
    private String code;

    StringWriter sw = new StringWriter();

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    @Override
    public void doTag() throws IOException, JspException {
        JspWriter out = getJspContext().getOut();
        HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getSession();
        String json = (String) session.getAttribute(Constants.DICTIONARY_SESSION_KEY);
        List<Dictionary> list = JSONObject.parseArray(json, Dictionary.class);
        getJspBody().invoke(sw);
        for (Dictionary obj : list) {
            if (obj.getDisType().equals(type) && obj.getDisCode().equals(sw.toString().trim())) {
                out.println(obj.getDisCodeName());
                return;
            }

        }
        out.println(sw.toString());
    }
}
